package es.duma.search;

import es.duma.util.log.Log;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SearchHandler extends DefaultHandler {
    
    private String element_value=null;
    public SearchObject busqueda;

    private static final String KEY="key";
    private static final String KEY_NOT="key-not";
    private static final String SERVICE="service";
    private static final String SEARCH="search";
    private static final String MAX_RESULTS="max-results";
    private static final String LANGUAGE="language";
    
    public SearchHandler(SearchObject busqueda){
        this.busqueda=busqueda;
    }

    
    public void startElement( String namespaceURI, String localName, String qName,Attributes attr ) throws SAXException{
        if (qName.equals(SEARCH)){
            if (attr!=null){
                String max_results=(String)attr.getValue(MAX_RESULTS);
                busqueda.setMaxResults(max_results);
                busqueda.setLanguage((String)attr.getValue(LANGUAGE));
            }
        }
    }
    
    
    public void endElement (String namespaceURI, String localName, String qName)throws SAXException{
        Log.debug(this,"name: "+namespaceURI+" local "+localName+" qname "+qName);
        if (qName.equals(KEY)){
            Log.debug(this,"Elemento encontrado: "+KEY);
            busqueda.addKey(element_value);
        }
        else if (qName.equals(KEY_NOT)){
            busqueda.addKeyNot(element_value);
        }
        else if (qName.equals(SERVICE)){
            busqueda.addService(element_value);
        }
        else if (qName.equals(SEARCH)){
        
            busqueda.setMaxResults(element_value);
            System.out.println(MAX_RESULTS);
        }
      }

    
    public void characters (char buf [], int offset, int len)throws SAXException
    {
       element_value = new String(buf, offset, len);
       element_value = element_value.trim();
    }

}

